package com.xiaoyu.lanling.feature.voicecall.service

import `in`.srain.cube.concurrent.AppThreads
import `in`.srain.cube.util.CLog
import android.app.Notification
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.xiaoyu.base.data.UserInfoDataProvider
import com.xiaoyu.lanling.common.Constant
import com.xiaoyu.lanling.data.NotificationData
import com.xiaoyu.lanling.event.voicecall.ChatCallServiceForegroundEvent
import com.xiaoyu.lanling.feature.voicecall.util.VoiceCallNotificationUtils
import com.xiaoyu.lanling.feature.voicecall.util.VoiceCallNotificationUtils.Companion.getNotificationText

class ChatCallService : Service() {

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent == null) {
            stop()
            return START_NOT_STICKY
        }
        val uid = intent.getStringExtra(Constant.PARAM_UID)
        val isCaller = intent.getBooleanExtra(Constant.IntentKey.KEY_CHAT_CALL_IS_CALLER, false)
        val isReceive = intent.getBooleanExtra(Constant.IntentKey.KEY_CHAT_CALL_IS_RECEIVE, false)
        showCallNotification(uid, isCaller, isReceive)
        return START_REDELIVER_INTENT
    }

    private fun showCallNotification(uid: String?, isCaller: Boolean, isReceive: Boolean) {
        if (uid == null) {
            stop()
            return
        }
        AppThreads.runOnIOThread(Runnable {
            val user = UserInfoDataProvider.getInstance().ensureAndGetUser(uid)
            val intent = VoiceCallNotificationUtils.instance.createChatVoiceIntent(uid, isCaller)
            val text = getNotificationText(isReceive)
            val notification = buildNotification(user.name, text, intent)
            startForeground(NotificationData.NotificationId.CALL_CHAT, notification)
            ChatCallServiceForegroundEvent().post()
        })
    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onDestroy() {
        CLog.i(TAG, "onDestroy()")
        super.onDestroy()
        stopForeground(true)
    }

    private fun stop() {
        stopForeground(true)
        stopSelf()
    }

    private fun buildNotification(title: String, text: CharSequence?, activityIntent: Intent?): Notification {
        val pendingIntent = PendingIntent.getActivity(applicationContext, 0, activityIntent, PendingIntent.FLAG_UPDATE_CURRENT)
        return VoiceCallNotificationUtils.instance.buildNotification(title, text, pendingIntent)
    }

    companion object {
        val TAG = ChatCallService::class.java.simpleName
    }
}